package com.cloud.mall.demos.sentinel;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cloud.mall.demos.web.User;
import com.cloud.mall.enums.ExcEnum;
import com.cloud.mall.exp.CustomException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: 梁二东
 * @Date: 2024/12/12 19:57
 * @Description:
 **/
@RestController
@RequestMapping("/ratelimit")
public class RateLimitController {

    @GetMapping("/rateLimitByUrl")
    public String rateLimitByUrl() {
        return "根据url限流";
    }

    @SentinelResource(value = "rateLimitByResource", blockHandler = "rateLimitByResourceBlockHandler", fallback = "fallbackMethod")
    @GetMapping("/rateLimitByResource")
    public String rateLimitByResource(@RequestParam(value = "version", defaultValue = "v0", required = false) String version) {
        if ("v1".equals(version)) {
            throw CustomException.fail(ExcEnum.NOT_FOUND);
        }
        return "根据SentinelResource限流";
    }

    public String rateLimitByResourceBlockHandler(String version, BlockException blockException) {
        return "触发限流，由rateLimitByResourceBlockHandler返回";
    }

    public String fallbackMethod(String version) {
        return "触发熔断，由fallbackMethod返回";
    }


    //---------------热点参数-get----(参数例外项)------------------
    @SentinelResource(value = "hotGetParam", blockHandler = "hotGetParamBlockHandler", fallback = "hotGetParamFallback")
    @GetMapping("/hotGetParam")
    public String hotGetParam(@RequestParam(value = "param1", required = false) String param1,
                              @RequestParam(value = "param2", required = false) String param2) {

        return "根据[热点参数-get]限流,param1[" + param1 + "],param2[" + param2 + "]";
    }

    public String hotGetParamBlockHandler(String param1, String param2, BlockException blockException) {
        return "触发限流，由 hotParamBlockHandler 返回";
    }

    public String hotGetParamFallback(String param1, String param2) {
        return "触发熔断，由 hotParamFallback 返回";
    }


    @SentinelResource(value = "hotPostParam")
    @PostMapping("/hotPostParam")
    public String hotPostParam(User user) {
        return "根据[热点参数-Post]限流";
    }

}
